package com.itheima.restkeeper.strategy.impl;

import com.itheima.restkeeper.constant.SuperConstant;
import com.itheima.restkeeper.enums.OrderEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Order;
import com.itheima.restkeeper.req.OrderVo;
import com.itheima.restkeeper.req.TradingVo;
import com.itheima.restkeeper.service.IOrderService;
import com.itheima.restkeeper.strategy.TradingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Version: V1.0
 */
@Component("tkTradingStrategy")
public class TkTradingStrategy implements TradingStrategy {

    @Autowired
    private IOrderService orderService;

    @Override
    public TradingVo convertorTradingVo(OrderVo orderVo) {
        Order order = orderService.getById(orderVo.getId());
        //修改退款金额
        order.setRefund(order.getRefund().add(orderVo.getOperTionRefund()));

        if (order.getRealAmountSum().longValue() < order.getRefund().longValue()) {
            throw new ProjectException(OrderEnum.REFUND_ERROR);
        }
        //有退款行为
        order.setIsRefund(SuperConstant.YES);
        ;
        boolean flag = orderService.updateById(order);
        //构建交易单
        if (flag) {
            TradingVo tradingVo = TradingVo.builder()
                    .operTionRefund(orderVo.getOperTionRefund())//前台传递过来退款金额
                    .tradingAmount(order.getRealAmountSum())//订单实付金额
                    .refund(order.getRefund())//订单退款金额
                    .isRefund(SuperConstant.YES)
                    .tradingChannel(orderVo.getTradingChannel())
                    .tradingType(orderVo.getTradingType())
                    .enterpriseId(orderVo.getEnterpriseId())
                    .productOrderNo(order.getOrderNo())
                    .memo(orderVo.getTableName() + ":" + orderVo.getOrderNo())
                    .build();
            return tradingVo;
        } else {
            throw new ProjectException(OrderEnum.UPDATE_FAIL);
        }
    }
}
